//
//  StudentMoreViewController.m
//  EducationAdminClient
//
//  Created by 孙添凤 on 16/9/7.
//  Copyright © 2016年 周佳兴. All rights reserved.
//

#import "StudentMoreViewController.h"
#import "Masonry.h"
#import "MySelfCell.h"
#import "MessageAlertViewController.h"
#import "ZCZBarViewController.h"
#import "ChangePassWordViewController.h"
#import "PersonInfoViewController.h"            // 个人资料
#import "FeedbackViewController.h"              // 反馈
#import "TZImagePickerController.h"
#import "ZMView.h"
#import <Photos/Photos.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "ListDetailViewController.h"
#import "SDImageCache.h"

#import "DemoVC9.h" // 朋友圈 测试
#define headHeight 236/2//头部背景高度（学员端）
#define headHeightTea 270/2//头部背景高度（教师端）
#define lineColor 0xd7d7d7
@interface StudentMoreViewController (){
    NSArray *labelArr;
    NSString *_campus;
    TZImagePickerController *imagePickerVc;
    NSString *_pageId;
    NSString *_tableId;
    float sss;
    BOOL    _isFromStudentMore;
    NSString *_imagePath;
    NSString *_fileCount;//文件个数
    
}
@property(nonatomic,strong)UILabel *name;
@property(nonatomic,strong)UILabel *tel;
@property(nonatomic,strong)UILabel *area;
@property(nonatomic,strong)UITableView *tbview;
@property(assign, nonatomic)BOOL   isCanChange;
@property(nonatomic,strong)NSMutableArray *CNName;//个人信息需要的cnname
@property(nonatomic,strong)NSDictionary *NextDictionary;//个人信息需要的Dic
@property(nonatomic,assign)NSInteger StarCount;//教师端星级个数
@property(nonatomic,strong)UIImageView *telImg;
@property(nonatomic,strong)UIImageView *areaImg;
@property(nonatomic,strong)UIView *headView;//底视图
@end

@implementation StudentMoreViewController

-(void)viewDidAppear:(BOOL)animated{
    self.cusTabView.userInteractionEnabled = YES;
    [super viewDidAppear:animated];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)])
    {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
        self.navigationController.interactivePopGestureRecognizer.delegate = self;
    }
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    if ([[userDefault valueForKey:@"autoLogin"]isEqualToString:@"autoLoginF"]) {
        [self showLabelWithText:@"自动登录失败"];
    }
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (!_CNName) {
        _CNName = [[NSMutableArray alloc] init];
    }
//    if (!_NextDictionary) {
//        _NextDictionary = [[NSDictionary alloc] init];
//    }else{
        _NextDictionary = personalDic();
//    }
    if (!_detailBtns) {
        _detailBtns = [[NSMutableArray alloc] init];
    }
    
    _isFromStudentMore = YES;
    self.cusTabView.hidden = NO;
    [_tbview reloadData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self dataRequest];
    _fileCount = [NSString string];
    // Do any additional setup after loading the view.
//    labelArr = @[@"个人资料",@"修改密码",@"意见反馈",@"清除缓存",@"当前版本",@"my_information",@"my_password",@"my_opinion",@"my_cache",@"my_news"];//这里是有反馈信息的代码
    //这里添加功能判断
    if (getEnglishLanguage()) {
        labelArr = @[@"Profile",@"Change Password",@"Clear Cache",@"Version",@"Friends",@"my_information",@"my_password",@"my_cache",@"my_news",@"my_news"];
    }else{
        labelArr = @[@"个人资料",@"修改密码",@"清除缓存",@"当前版本",@"朋友圈",@"my_information",@"my_password",@"my_cache",@"my_news",@"my_news"];
    }
    
    [self creatNavButton];
    [self creatHeadUI];
    [self creatUI];
    //#ifdef Main
    _imgArr = [[NSMutableArray alloc] init];
    _imagePaths = [[NSMutableArray alloc] init];
    _picArr = [[NSMutableArray alloc] init];
    //#ifdef Main
    
    if([getUIStyle() isEqualToString:STYLE0]){
        //这里添加功能判断
        if (getEnglishLanguage()) {
            [self setTitleLabelText:@"Me"];
        }else{
            [self setTitleLabelText:@"我的"];
        }

        
    }else{
        
        //#elif Student
        
        [self setTitleLabelText:@"我的"];
    }
    //#elif Teacher
    //    //    rootview
    //    NSLog(@"老师端程序");
    //#else
    //
    //    NSLog(@"都不是");
    //#endif
    
    //
    //
    //    UIButton *btn1 =[UIButton  buttonWithType:UIButtonTypeSystem];
    //    [self.view addSubview:btn1];
    //    [btn1 mas_makeConstraints:^(MASConstraintMaker *make) {
    //
    //        make.centerX.equalTo(self.view.mas_centerX);
    //        make.top.equalTo(btn.mas_bottom).offset(50);
    //        make.width.equalTo(@(150));
    //        make.height.equalTo(@(40));
    //    }];
    //    btn1.backgroundColor = [UIColor colorWithRed:0xff/256.0f green:0x5e/256.0f blue:0x5e/256.0f alpha:1];
    //    btn1.titleLabel.font = [UIFont systemFontOfSize:16];
    //    [btn1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    //    [btn1 setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    //    [btn1 setTitle:@"清除缓存" forState:UIControlStateNormal];
    //    [btn1 addTarget:self action:@selector(clean:) forControlEvents:UIControlEventTouchUpInside];
    //    btn1.layer.cornerRadius = 8;
    NSLog(@"changes");
}

-(void)dataRequest{
    
    NSString *requestUrl;
    NSMutableDictionary *parama =[[NSMutableDictionary alloc]init];
    
    
    
    
    if ([getUIStyle() isEqualToString:STYLE0]) {
        //        NSMutableDictionary *parmas = [[NSMutableDictionary alloc]init];
        NSDictionary *personDictionary = personDic();
        NSLog(@"%@",personDictionary);
        _tableId = [NSString stringWithFormat:@"%@",[personDictionary objectForKey:@"tableId"]];
        _pageId = [NSString stringWithFormat:@"%@",[personDictionary objectForKey:@"pageId"]];
        if (![_tableId isEqualToString:@""]) {
            [parama setObject:_tableId forKey:@"tableId"];
        }
        if (![_pageId isEqualToString:@""]) {
            [parama setObject:_pageId forKey:@"pageId"];
        }
        
        //        [parama setObject:@"2873" forKey:@"pageId"];
        //        [parama setObject:@"2" forKey:@"tableId"];
    }else{
        NSDictionary *personDictionary = personDic();
        NSLog(@"%@",personDictionary);
        _tableId = [NSString stringWithFormat:@"%@",[personDictionary objectForKey:@"tableId"]];
        _pageId = [NSString stringWithFormat:@"%@",[personDictionary objectForKey:@"pageId"]];
        if (![_tableId isEqualToString:@""]) {
            [parama setObject:_tableId forKey:@"tableId"];
        }
        if (![_pageId isEqualToString:@""]) {
            [parama setObject:_pageId forKey:@"pageId"];
        }
        
//        [parama setObject:@"2512" forKey:@"pageId"];124.254.63.60:8874/edus_auto/model_interfaceToList.do?alterTime=&limit=20&loginName=cmcs001&pageId=3573&password=000000&start=0&tableId=2
//        [parama setObject:@"19" forKey:@"tableId"];
    }
    
    
    requestUrl = [NSString stringWithFormat:@"%@%@", self.programaUrl, PERSONAL_INFO_URl];
    [NetRequest requestUrl:requestUrl andParamas: parama andReturnBlock:^(NSData *data, NSError *error) {
        
        if(data!=nil&&!error){
            
            NSLog(@"%@",data);
            NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@",str);
            NSDictionary *obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSString *strData = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@", strData);
            NSArray *fieldCnNameArray = [[obj objectForKey:@"pageSet"] objectForKey:@"fieldSet"];
            NSString *fieldAliasName;
            NSString *starName;
            for (NSDictionary *diction in fieldCnNameArray) {
                NSRange range = [[diction objectForKey:@"fieldCnName"] rangeOfString:@"校区"];
                if (range.length>0) {
                    fieldAliasName = [diction objectForKey:@"fieldAliasName"];
                    break;
                }
            }
            if ([getUIStyle() isEqualToString:STYLE0]) {
                for (NSDictionary *diction in fieldCnNameArray) {
                    NSRange range = [[diction objectForKey:@"fieldCnName"] rangeOfString:@"Rank"];
                    if (range.length>0) {
                        starName = [diction objectForKey:@"fieldAliasName"];
                        break;
                    }
                }
            }
            
            
            
            NSLog(@"%@",obj);
            // 数据处理，当没问题的情况下
            [self dataUse:obj andFieldAliasName:fieldAliasName];
            
            //这里添加UI判断
            if (getPersonalInformationStarUI()) {
                [self starDateUse:obj andFieldAliasName:starName];
            }
            
            
        }else{
            NSString *str = [NSString stringWithFormat:@"%@", error.localizedDescription];
            [self showLabelWithText:str];
            [self changePersonalInfomation];
        }
        
        
    }];
}

- (void)starDateUse:(id)obj andFieldAliasName:(NSString *)name{
    NSArray *arr =[obj objectForKey:@"dataList"];
    NSLog(@"%@",name);
    NSDictionary * dic;
    if (arr.count>0) {
        dic =arr[0];
    }
    //    NSString *campus;
    if ([dic objectForKey:name]) {
        
        //这里添加功能判断
        if (getPersonalInformationStarUI()) {
            NSString *count = [NSString stringWithFormat:@"%@",[dic objectForKey:name]];
            for (int i = 0; i < [count intValue]; i++) {
                UIImageView *starBgView = [[UIImageView alloc] init];
                [_headView addSubview:starBgView];
                [starBgView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(_areaImg.mas_bottom).offset(20/2);
                    make.left.equalTo(_areaImg.mas_left).offset(i*(29/2+10/2));
                    make.width.equalTo(@(29/2));
                    make.height.equalTo(@(29/2));
                }];
                starBgView.image = [UIImage imageNamed:@"teaStar"];
                
            }
            
        }
    }else{
//        _campus = @"暂无校区";
    }

}

-(void)dataUse:(id)obj andFieldAliasName:(NSString *)name{
    //    dataArr = [[obj objectForKey:@"pageSet"]objectForKey:@"fieldSet"];
    NSArray *arr =[obj objectForKey:@"dataList"];
    NSLog(@"%@",name);
    NSDictionary * dic;
    if (arr.count>0) {
        dic =arr[0];
    }
    NSString *NoSchoolStr;
    //这里添加功能判断
    if (getEnglishLanguage()) {
        NoSchoolStr = @"No School";
    }else{
        NoSchoolStr = @"暂无校区";
    }

    //    NSString *campus;
    if (dic) {
        if (name) {
            _campus = [NSString stringWithFormat:@"%@",[dic objectForKey:name]];
        }else{
            _campus = NoSchoolStr;
        }
    }else{
        _campus = NoSchoolStr;
    }
    
    
    if (_campus) {
        _area.text = _campus;
    }else{
        _area.text = NoSchoolStr;
    }
    
    [self changePersonalInfomation];
    
    
    //    [self.tbView reloadData];
}

-(void)changePersonalInfomation{
    self.CNName = cnName();
    self.NextDictionary = personalDic();
    self.detailBtns = detailBtns();
    NSString *change = getUserChange();
    if (_CNName&&_NextDictionary&&_detailBtns.count>0&&[change isEqualToString:@"NO"]) {
        NSLog(@"有数据，可以直接调用");
        _isCanChange = YES;
    }else{
        
        NSDictionary *personDictionary = personDic();
        NSLog(@"%@",personDictionary);
        if (!_tableId) {
            _tableId = [NSString stringWithFormat:@"%@",[personDictionary objectForKey:@"tableId"]];
        }
        if (!_pageId) {
            _pageId = [NSString stringWithFormat:@"%@",[personDictionary objectForKey:@"pageId"]];
        }
        
        
        
        
        if (!_tableId||!_pageId) {
            _isCanChange = NO;
            return;
        }else{
            _isCanChange = YES;
        }
        NSMutableDictionary *parmas = [[NSMutableDictionary alloc]init];
        NSDictionary *savePageSetDic;
        NSDictionary *saveDic;

        NSString *path3;
        NSString *pathForPageSet;
        NSString *path2= myselfSaveFile(userName(), @"lists", @"lists.plist");
        
        path3 = [path2 stringByAppendingPathComponent:[NSString stringWithFormat:@"listFor%@%@.plist", _tableId, _pageId]];
        
        pathForPageSet = [path2 stringByAppendingPathComponent:[NSString stringWithFormat:@"listFor%@%@pageSet.plist", _tableId, _pageId]];
        
        NSData *saveData = [NSData dataWithContentsOfFile:path3];
        if(saveData) saveDic = [NSJSONSerialization JSONObjectWithData:saveData options:NSJSONReadingMutableContainers error:nil];
        savePageSetDic = [[NSDictionary alloc]initWithContentsOfFile:pathForPageSet];
        
        [parmas setObject:userName() forKey:@"loginName"];
        [parmas setObject:passWord() forKey:@"password"];
        [parmas setObject:@"" forKey:@"alterTime"];
        [parmas setObject:[NSString stringWithFormat:@"%i", 20] forKey:@"limit"];
        [parmas setObject:[NSString stringWithFormat:@"%i", 0] forKey:@"start"];
        [parmas setObject:_pageId forKey:@"pageId"];
        [parmas setObject:_tableId forKey:@"tableId"];
        
        
        
        
        NSString *loginName = userName();
        NSString *LoginPassWord = passWord();
        NSString *requestUrl = [NSString stringWithFormat:@"%@%@", self.programaUrl, LISTSVIEWREQUEST_URL];
//        NSString *urlStr = [NSString stringWithFormat:@"http://124.254.63.60:8874/edus_auto/model_interfaceToList.do?alterTime=&limit=20&loginName=%@&password=%@&pageId=%d&start=0&tableId=%d",loginName,LoginPassWord,_tableId.intValue,_pageId.intValue];//(学员端接口500错误)
        [NetRequest requestUrl:requestUrl andParamas:parmas andReturnBlock:^(NSData *data, NSError *error) {
            if (data!=nil&&!error) {
                NSDictionary *obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                
                NSMutableArray *currwntDataArr = [NSMutableArray arrayWithArray:[obj objectForKey:@"dataList"]];
                if([obj valueForKey:@"pageSet"]!=nil){
                    
                    _CNName = [NSMutableArray arrayWithArray:[[obj valueForKey:@"pageSet"]valueForKey:@"fieldSet"]];
                    
                }
                
                
                NSMutableArray *btnArrDetail = [[obj valueForKey:@"pageSet"] valueForKey:@"operaButtonSet"];
                
                NSMutableArray *btnArrDetailU = [[NSMutableArray alloc]initWithArray:btnArrDetail];
                for (NSDictionary *dic in btnArrDetailU) {
                    NSString *str = [NSString stringWithFormat:@"%@_%@", _pageId, [dic valueForKey:@"buttonId"]];
                    BOOL can = textButton(str);
                    if (!can&&![userName() isEqualToString:@"admin"]) {
                        [btnArrDetail removeObject:dic];
                    }
                }
                _detailBtns = btnArrDetail;
                if (_detailBtns.count>0) {
                    saveDetailBtns(_detailBtns);
                }
                _NextDictionary = [currwntDataArr firstObject];
                if (_CNName&&_NextDictionary) {
                    saveCnName(_CNName);
                    savePersonalDic(_NextDictionary);
                }
                NSLog(@"nsmutabearray:%@ nsdictionary:%@",cnName(),personalDic());
            }
        }];
    }
}
-(void)creatNavButton{
#if Student
    UIButton *leftNavBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftNavBtn.frame = CGRectMake(0, 0, 22, 22);
    leftNavBtn.hidden = YES;//隐藏扫码
    [leftNavBtn setBackgroundImage:[UIImage imageNamed:@"nav_scan_code"] forState:UIControlStateNormal];
    [leftNavBtn addTarget:self action:@selector(LeftClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:leftNavBtn];
    self.navigationItem.leftBarButtonItem = item;
#endif
    //右侧消息按钮
//    UIButton *rightNavBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    rightNavBtn.frame = CGRectMake(0, 0, 22, 22);
//    [rightNavBtn setBackgroundImage:[UIImage imageNamed:@"nav_news"] forState:UIControlStateNormal];
//    [rightNavBtn addTarget:self action:@selector(RightClick:) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *item2 = [[UIBarButtonItem alloc]initWithCustomView:rightNavBtn];
//    self.navigationItem.rightBarButtonItem = item2;
    
    
}

- (void)LeftClick:(UIButton *)sender{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authStatus == AVAuthorizationStatusDenied||authStatus == AVAuthorizationStatusRestricted) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请允许该应用使用相机\n方法：设置->隐私->相机" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alert show];
            return ;
        }
    }
    
    ZCZBarViewController *zvc = [[ZCZBarViewController alloc] initWithBlock:^(NSString * data, BOOL succeed) {
        if(succeed){
            NSString *urlStr = [[NSString alloc]initWithString:data];
            NSLog(@"%@", urlStr);
            
            //                NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
            //                [param setObject:str forKey:@"stuId"];
            
            [NetRequest requestUrl:urlStr andParamas:nil andReturnBlock:^(NSData *data, NSError *error) {
                if(!error&&data!=nil){
                    NSString *str = [[NSString alloc]initWithData:data  encoding:NSUTF8StringEncoding];
                    NSDictionary *obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                    NSLog(@"%@", obj);
                    if ([str isEqualToString:@"1"]) {
                        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"考勤" message:@"考勤成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                        alert.delegate = self;
                        [alert show];
                    }else{
                        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"考勤" message:str delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                        alert.delegate = self;
                        [alert show];
                    }
                    NSLog(@"sucess!");
                    //                    _sucess = YES;
                }else{
                    
                    NSString *str = [NSString stringWithFormat:@"系统错误！%@",urlStr];
                    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"考勤" message:str delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                    alert.delegate = self;
                    [alert show];
                    NSLog(@"%@",error);
                    //                    _sucess = NO;
                }
                
            }];
            //            NSLog(@"%@",erro);
            
        }
        
    }];
    
    [self.navigationController presentViewController:zvc animated:YES completion:^{
        
    }];;
}
- (void)RightClick:(UIButton *)sender{
    MessageAlertViewController *mavc = [[MessageAlertViewController alloc] init];
    mavc.tabbarView = self.cusTabView;
    [self.navigationController pushViewController:mavc animated:YES];
}

#pragma mark - 获取本地头像方法
- (UIImage *)getLocalIcon{
    NSString *paths = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSLog(@"%@",paths);
    NSRange range = [_imagePath rangeOfString:@"Documents"];
    NSRange needRange = NSMakeRange(0, range.location+range.length);
    NSLog(@"%@",_imagePath);
    _imagePath = [_imagePath stringByReplacingCharactersInRange:needRange withString:paths];//每次更换沙盒路径需要重新替换新的路径，否则找不到文件。
    NSLog(@"%@",_imagePath);
    
    UIImage *photoImg = [[UIImage alloc]initWithContentsOfFile:_imagePath];
    return photoImg;

}

-(void)creatHeadUI{
    if (!_headView) {
        _headView =[[UIView alloc]init];
        [self.view addSubview:_headView];
    }
    
    
    [_headView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.top.equalTo(self.view.mas_top).offset(10);
        //这里添加功能判断
        if (getPersonalInformationStarUI()) {
            make.height.equalTo(@(headHeightTea));
        }else{
            make.height.equalTo(@(headHeight));
        }
        
    }];
    _headView.backgroundColor =[UIColor whiteColor];
    
    UIView *topLine =[[UIView alloc]init];
    [_headView addSubview:topLine];
    [topLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.top.equalTo(_headView.mas_top);
        make.height.equalTo(@(1));
    }];
    topLine.backgroundColor =[UIColor colorWithHex:lineColor];
    
    UIView *bottomLine =[[UIView alloc]init];
    [_headView addSubview:bottomLine];
    [bottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.bottom.equalTo(_headView.mas_bottom);
        make.height.equalTo(@(1));
    }];
    bottomLine.backgroundColor =[UIColor colorWithHex:lineColor];
    
    _headImg =[[UIImageView alloc]init];
    _headImg.layer.masksToBounds = YES;
    _headImg.layer.cornerRadius = 8.0f;
    [_headView addSubview:_headImg];
    [_headImg sizeToFit];
    [_headImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_headView.mas_centerY);
        make.left.equalTo(_headView.mas_left).offset(21);
        make.width.equalTo(@(168/2));
        make.height.equalTo(@(168/2));
    }];
    //这里添加头像功能判断
    if (getAvatarUpload()) {
        if (_imagePath) {
            UIImage *photoImg = [[UIImage alloc]initWithContentsOfFile:_imagePath];
            _headImg.image =photoImg;
        }else{
            if (userIcon()) {
                _imagePath = userIcon();
                if (_imagePath == nil) {
                    NSLog(@"需要请求");
                    [self requestUserIconAndSave];
                    
                }else{
                    _headImg.image = [self getLocalIcon];
                }
                
                
            }else{
                _headImg.image =[UIImage imageNamed:@"my_portrait_normal"];
            }
            
        }

    }else{
        _headImg.image =[UIImage imageNamed:@"my_portrait_normal"];
    }

    
    
    _headImg.userInteractionEnabled = YES;
    UIButton *imageBtn = [[UIButton alloc] init];
    imageBtn.backgroundColor = [UIColor clearColor];
    [_headImg addSubview:imageBtn];
    [imageBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_headImg);
    }];
#pragma mark - 屏蔽学员端更换头像功能
    [imageBtn addTarget:self action:@selector(imageBtnClick) forControlEvents:UIControlEventTouchUpInside];
    //这里添加头像功能判断
    if (getAvatarUpload()) {
//    if ([getUIStyle() isEqualToString:STYLE0]) {
        imageBtn.hidden = NO;
    }else{
        imageBtn.hidden = YES;
    }
    
    
    _name =[[UILabel alloc]init];
    [_headView addSubview:_name];
    [_name mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_headImg.mas_right).offset(14);
        //这里添加功能判断
        if (getPersonalInformationStarUI()) {
            make.top.equalTo(_headImg.mas_top);
        }else{
            make.top.equalTo(_headImg.mas_top).offset(14/2);
        }
        make.height.equalTo(@(34/2));
        
    }];
    //    _name.text = @"李小明";
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSString *StuName = [ud objectForKey:@"username"];
    if (StuName) {
        _name.text = StuName;
    }else{
        _name.text = @"李小明";
    }
    
    _name.textColor =[UIColor colorWithHex:0x333333];
    _name.font =[UIFont systemFontOfSize:17];
    
    _telImg =[[UIImageView alloc]init];
    [_headView addSubview:_telImg];
    [_telImg sizeToFit];
    [_telImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_headImg.mas_right).offset(12);
        //这里添加功能判断
        if (getPersonalInformationStarUI()) {
            make.top.equalTo(_name.mas_bottom).offset(20/2);
        }else{
            make.top.equalTo(_name.mas_bottom).offset(16);
        }
        
    }];
    
    if([getUIStyle() isEqualToString:STYLE0]){
        _telImg.image =[UIImage imageNamed:@"my_personnel"];
    }else{
        _telImg.image =[UIImage imageNamed:@"my_phone"];
    }
    
    
    _tel =[[UILabel alloc]init];
    [_headView addSubview:_tel];
    [_tel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset((42+172+24+12+24)/2+1);
        make.right.equalTo(self.view.mas_right).offset(-18);
//        if ([getUIStyle() isEqualToString:STYLE0]) {
            make.top.equalTo(_telImg.mas_top).offset(-2);
//        }else{
//            make.top.equalTo(_telImg.mas_top);
//            _tel.backgroundColor = [UIColor redColor];
//        }
        
    }];
    //    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSString *phone;
    //这里添加功能判断
    if (getEnglishLanguage()) {
        phone = rolenames();
        if (phone) {
            _tel.text = phone;
            if ([phone isEqualToString:@"教师"]) {
                _tel.text = @"Teacher";
            }
        }else{
            _tel.text = @"暂无角色信息";
        }
    }else{
        phone = [ud objectForKey:@"user"];
        if (phone) {
            _tel.text = phone;
        }else{
            _tel.text = @"13866666666";
        }
    }
    
    
    
    _tel.textColor =[UIColor colorWithHex:0x858585];
    _tel.font =[UIFont systemFontOfSize:16];
    
    _areaImg =[[UIImageView alloc]init];
    [_headView addSubview:_areaImg];
    [_areaImg sizeToFit];
    [_areaImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_headImg.mas_right).offset(12);
        //这里添加功能判断
        if (getPersonalInformationStarUI()) {
            make.top.equalTo(_telImg.mas_bottom).offset(16/2);
        }else{
            make.top.equalTo(_telImg.mas_bottom).offset(10);
        }
        
    }];
    
    
    if([getUIStyle() isEqualToString:STYLE0]){
        _areaImg.image =[UIImage imageNamed:@"my_position1"];
    }else{
        _areaImg.image =[UIImage imageNamed:@"my_position"];
    }
    
    
    _area =[[UILabel alloc]init];
    //    _tel.backgroundColor = [UIColor purpleColor];
    [_headView addSubview:_area];
    [_area mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset((42+172+24+12+24)/2+1);
        make.right.equalTo(self.view.mas_right).offset(-18);
        //        make.left.equalTo(areaImg.mas_right).offset(6);
        //        make.right.equalTo(self.view.mas_right).offset(-36/2);
        make.top.equalTo(_areaImg.mas_top).offset(-2);
    }];
    //    _area.backgroundColor = [UIColor purpleColor];
    //    [_area setContentHuggingPriority:UILayoutPriorityRequired
    //                                   forAxis:UILayoutConstraintAxisHorizontal];//宽度够的时候优先级宽度根据label内容
    //    [_area setContentCompressionResistancePriority:UILayoutPriorityRequired
    //                                                 forAxis:UILayoutConstraintAxisHorizontal];
    _area.textColor =[UIColor colorWithHex:0x858585];
    _area.font =[UIFont systemFontOfSize:16];
    //这里添加功能判断
    if (getPersonalInformationStarUI()) {
        for (int i = 0; i < 5; i++) {
            
            UIImageView *starBgView = [[UIImageView alloc] init];
            if (i == 0) {
                
            }
            [_headView addSubview:starBgView];
            [starBgView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(_areaImg.mas_bottom).offset(20/2);
                make.left.equalTo(_areaImg.mas_left).offset(i*(29/2+10/2));
                make.width.equalTo(@(29/2));
                make.height.equalTo(@(29/2));
            }];
            starBgView.image = [UIImage imageNamed:@"teabgStar"];
            
        }
        
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    if(indexPath.row==3){
    
    if(indexPath.row==2){
        if(CURRENTVERSION <9.0){//This is an irreversible operation. Are you sure to delete?
            UIAlertView *alert;
            //这里添加功能判断
            if (getEnglishLanguage()) {
                alert = [[UIAlertView alloc]initWithTitle:nil message:@"This is an irreversible operation. Are you sure to delete?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Delete", nil];
            }else{
                alert = [[UIAlertView alloc]initWithTitle:nil message:@"是否确认删除" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"确定", nil];
            }
            alert.delegate = self;
            [alert show];
        }else{
            UIAlertController *alertController;
            //这里添加功能判断
            if (getEnglishLanguage()) {
                alertController = [UIAlertController alertControllerWithTitle:nil message:@"This is an irreversible operation. Are you sure to delete?" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction1 = [UIAlertAction actionWithTitle:@"Delete" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    NSLog(@"delete");
                    
                    [self removeCashes];
                    
                    
                }];
                
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                [alertController addAction:cancelAction];
                [alertController addAction:cancelAction1];
                [self presentViewController:alertController animated:YES completion:^{
                    
                }];
            }else{
                alertController = [UIAlertController alertControllerWithTitle:nil message:@"是否确认删除" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction1 = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    NSLog(@"delete");
                    
                    [self removeCashes];
                    
                    
                }];
                
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                [alertController addAction:cancelAction];
                [alertController addAction:cancelAction1];
                //presentViewController这个方法有可能不是在UI线程执行的  加入主线程代码
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self presentViewController:alertController animated:YES completion:^{
                        
                    }];
                });
                
            }
            
            
            
            
        }
        
    }
    else if (indexPath.row==1){
        ChangePassWordViewController *cp = [[ChangePassWordViewController alloc] init];
        cp.cusTabView = self.cusTabView;
        [self.navigationController pushViewController:cp animated:YES];
    }else if(indexPath.row == 4){
        DemoVC9 *frientsVC = [[DemoVC9 alloc]init];
        [self.navigationController pushViewController:frientsVC animated:YES];
        
    }
    else if (indexPath.row==0){
        
//        PersonInfoViewController *pv =[[PersonInfoViewController alloc]init];
//        pv.cusTabView = self.cusTabView;
//        [self.navigationController pushViewController:pv animated:YES];
        ListDetailViewController *listDVC =[[ListDetailViewController alloc]init];
        
//        if (self.TeacherNeedDownLoad == YES) {
//            listDVC.TeacherNeedDownLoad = YES;
//        }
        if ([getUIStyle() isEqualToString:STYLE1]) {
                    PersonInfoViewController *pv =[[PersonInfoViewController alloc]init];
                    pv.cusTabView = self.cusTabView;
            [self.navigationController pushViewController:pv animated:YES];
        }else{
            if (!_isCanChange) {
                return;
            }
            NSDictionary *personDictionary = personDic();
            NSLog(@"%@",personDictionary);
            NSString *tableId = [NSString stringWithFormat:@"%@",[personDictionary objectForKey:@"tableId"]];
            NSString *pageId = [NSString stringWithFormat:@"%@",[personDictionary objectForKey:@"pageId"]];
            listDVC.cusTabView = self.cusTabView;
            listDVC.retureView = self;
            if (_CNName) {
                listDVC.cnName = _CNName;
            }
            if (_NextDictionary) {
                listDVC.detailDic = _NextDictionary;
            }else{
                return;
            }
            if (self.detailBtns.count>0) {
                listDVC.buttons = _detailBtns;
            }
            listDVC.detailTitle = @"个人资料";
            listDVC.isFromStudentMore = YES;
            //        listDVC.buttons = _detailBtns;
            listDVC.tableId = tableId;
            listDVC.pageId = pageId;
            [self.navigationController pushViewController:listDVC animated:YES];
        }
        
        
        
        
        
        
//        self.isPop = @"detail";
//        listDVC.isNeedDownload = _isNeedDownload;
        
//        NSDictionary *dic= [_fieldArr objectAtIndex:indexPath.row];
//        listDVC.detailDic = dic;
        self.selecCell = YES;
        
        [tableView deselectRowAtIndexPath:indexPath animated:YES];

        
        
        
    }
#pragma mark - 反馈页面跳转
//        else if (indexPath.row == 2){
//
//        FeedbackViewController *fbvc = [[FeedbackViewController alloc] init];
//        fbvc.cusTabView = self.cusTabView;
//        [self.navigationController pushViewController:fbvc animated:YES];
//        
//    }else{
       
//    }
}

-(void)creatUI{
    
    UIView *topLine2 =[[UIView alloc]init];
    [self.view addSubview:topLine2];
    [topLine2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        //这里添加功能判断
        if (getPersonalInformationStarUI()) {
            make.top.equalTo(self.view.mas_top).offset(headHeightTea+19);
        }else{
            make.top.equalTo(self.view.mas_top).offset(headHeight+19);
        }
        
        make.height.equalTo(@(1));
    }];
    topLine2.backgroundColor =[UIColor colorWithHex:lineColor];
    
    _tbview =[[UITableView alloc]init];
    [self.view addSubview:_tbview];
    _tbview.delegate = self;
    _tbview.dataSource = self;
    [_tbview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        //这里添加功能判断
        if (getPersonalInformationStarUI()) {
            make.top.equalTo(self.view.mas_top).offset(headHeightTea+20);
        }else{
            make.top.equalTo(self.view.mas_top).offset(headHeight+20);
        }
        
        make.bottom.equalTo(self.view.mas_bottom).offset(-50);
    }];
    _tbview.separatorStyle = NO;
    _tbview.tableFooterView = [self createCollectionViewHeaderView];
    
    
}


- (UIView *)createCollectionViewHeaderView{
    UIView *superView = [[UIView alloc] init];
    superView.backgroundColor = [UIColor whiteColor];
    
    superView.frame = CGRectMake(0, 0, self.tbView.frame.size.width, (80+84+50)/2);
    //    UIView *bottomView =[[UIView alloc]init];
    //    [self.view addSubview:bottomView];
    //    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.top.equalTo(_tbview.mas_bottom);
    //        make.left.equalTo(self.view.mas_left);
    //        make.right.equalTo(self.view.mas_right);
    //        make.bottom.equalTo(self.view.mas_bottom).offset(-50);
    //    }];
    //    bottomView.backgroundColor =[UIColor whiteColor];
    
    UIButton *btn =[[UIButton alloc]init];
    [superView addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(superView.mas_top).offset(80/2);
        //        make.bottom.equalTo(self.view.mas_bottom).offset(-50-25);
        make.height.equalTo(@(84/2));
        make.left.equalTo(superView.mas_left).offset(30/2);
        make.right.equalTo(superView.mas_right).offset(-30/2);
        //        make.height.equalTo(@(41.5));
    }];
    [btn setBackgroundColor:[UIColor whiteColor]];
    btn.layer.borderWidth = 0.5;
    btn.layer.cornerRadius = 6;
    btn.layer.borderColor =[[UIColor colorWithHex:0xef5152]CGColor];
    [btn addTarget:self action:@selector(exitClick:) forControlEvents:UIControlEventTouchUpInside];
    //这里添加功能判断
    if (getEnglishLanguage()) {
        [btn setTitle:@"Log Out" forState:UIControlStateNormal];
    }else{
        [btn setTitle:@"退出登录" forState:UIControlStateNormal];
    }

    
    [btn setTitleColor:[UIColor colorWithHex:0xef5152] forState:UIControlStateNormal];
    btn.titleLabel.font =[UIFont systemFontOfSize:18];
    
    return superView;
}

#pragma mark - 下面两个获取文件大小的返回值都是数据类型,可以用NSString stringWithFormat转换成字符串
-(float)getFilePath{
    
    //文件管理
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    //缓存路径
    
    //    NSArray *cachePaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES);
    NSString *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)[0];
    
    NSString *imageDir = [NSString stringWithFormat:@"%@/%@/", paths, userName()];
    NSString *cacheDir = imageDir;
    
    NSArray *cacheFileList;
    
    NSEnumerator *cacheEnumerator;
    
    NSString *cacheFilePath;
    
    unsigned long long cacheFolderSize = 0;
    
    cacheFileList = [fileManager subpathsOfDirectoryAtPath:cacheDir error:nil];
    
    cacheEnumerator = [cacheFileList objectEnumerator];
    
    while (cacheFilePath = [cacheEnumerator nextObject]) {
        
        NSDictionary *cacheFileAttributes = [fileManager attributesOfItemAtPath:[cacheDir stringByAppendingPathComponent:cacheFilePath] error:nil];
        
        cacheFolderSize += [cacheFileAttributes fileSize];
        
    }
    
    //单位MB
    
    return cacheFolderSize/1024;
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"identifier";
    //    [tableView registerClass:[MySelfCell class] forCellReuseIdentifier:identifier];
    static int times = 0;
    MySelfCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[MySelfCell alloc] initWithReuseIdentifier:identifier];
        
        //        [cell initWithReuseIdentifier:identifier];
        
    }
    //    if (indexPath.row == 3) {
    //        if (indexPath.row == 3) {
    //            cell.versionLabel.text = [NSString stringWithFormat:@"%zd",[self getFilePath]];
    //            cell.versionLabel.hidden = NO;
    //        }
    //    }else{
    //        if (indexPath.section == 1) {
    //
    //        }
    //    }
    
//    if(indexPath.row >2)
    if(indexPath.row >1)
    {
        cell.arrow.hidden = YES;
        cell.versionLabel.hidden = NO;
        //        cell.label.text = @"版本号";
        //        NSString *imgStr  = [labelArr objectAtIndex:indexPath.row+5];
        //        cell.img.image =[UIImage imageNamed:imgStr];
//        if (indexPath.row == 3) {
        if (indexPath.row == 2) {
            if ([self getFilePath]>1000) {
                cell.versionLabel.text = [NSString stringWithFormat:@"%.2fMB",[self getFilePath]/1024];
            }else{
                cell.versionLabel.text = [NSString stringWithFormat:@"%.2fKB",[self getFilePath]];
            }
            
        }
    }else{
        cell.arrow.hidden = NO;
        cell.versionLabel.hidden = YES;
        
        
        
    }
//    NSString *imgStr  = [labelArr objectAtIndex:indexPath.row+5];
    NSString *imgStr  = [labelArr objectAtIndex:indexPath.row+4];
    cell.label.text = [labelArr objectAtIndex:indexPath.row];
    cell.img.image = [UIImage imageNamed:imgStr];
    
    if (nil == cell) {
        // HERE
        times ++;
        NSLog(@"time :%d ",times);
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //return 5;//这里是有反馈信息的代码
    return 5;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row <5) {
        return 50.5;
    }
    return (84+80+1+80)/2;
}

-(void)clean:(UIButton *)btn{
    
    
    if(CURRENTVERSION <9.0){
        UIAlertView *alert =[[UIAlertView alloc]initWithTitle:nil message:@"是否确认删除" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"确定", nil];
        alert.delegate = self;
        [alert show];
    }else{
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"是否确认删除" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *cancelAction1 = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"delete");
            
            [self removeCashes];
            
            
        }];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertController addAction:cancelAction];
        [alertController addAction:cancelAction1];
        [self presentViewController:alertController animated:YES completion:^{
            
        }];
        
    }
    
    
    
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        [self removeCashes];
        
    }
}

-(void)removeCashes{
    BOOL removeCashes = removeCaches(userName());
#pragma mark - 清除个人信息相关NSUserDefaults
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    
//    NSString *path = userIcon();
//    
////    NSString *imageDir = [NSString stringWithFormat:@"%@/%@/", paths, userName];
//    NSFileManager *fileManager = [NSFileManager defaultManager];
//    
//    BOOL isDir = NO;
//    BOOL existed = [fileManager fileExistsAtPath:path isDirectory:&isDir];
//    
//    if(existed){
//        BOOL success = [fileManager removeItemAtPath:path error:nil];
//        NSLog(@"是否删除成功");
////        return success;
//    }else{
////        return YES;
//        
//    }
//    NSString *usericon = userIcon();
//    NSString *paths = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
//    NSLog(@"%@",paths);
//    NSRange range = [usericon rangeOfString:@"Documents"];
//    NSRange needRange = NSMakeRange(0, range.location+range.length);
//    usericon = [usericon stringByReplacingCharactersInRange:needRange withString:paths];
//    
//    NSLog(@"%@",usericon);
//    
//    NSFileManager *fileMgr = [NSFileManager defaultManager];
//    BOOL bRet = [fileMgr fileExistsAtPath:usericon];
//    if (bRet) {
//        //
//        NSError *err;
//        [fileMgr removeItemAtPath:usericon error:&err];
//    }
    
    
    [ud removeObjectForKey:@"personalDic"];//个人信息页面数据
    [ud removeObjectForKey:@"cnName"];//个人信息页面相关显示
    [ud removeObjectForKey:@"detailBtns"];//清除个人信息页面按钮
//    [ud removeObjectForKey:@"userIcon"];//清除数据是否清除头像
    [ud synchronize];
    NSString *usericon1 = userIcon();
    
    NSString *messageStr = @"";
    NSString *OKStr = @"";
    //这里添加功能判断
    if (getEnglishLanguage()) {
//    if ([getUIStyle() isEqualToString:@"0"]) {
        OKStr = @"OK";
        if (removeCashes) {
            messageStr = @"success";
            [_tbview reloadData];
        }else{
            messageStr = @"fail";
        }
    }else{
        OKStr = @"确定";
        if (removeCashes) {
            messageStr = @"成功";
            [_tbview reloadData];
        }else{
            messageStr = @"失败";
        }
    }
    
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue addOperationWithBlock:^{
        SDImageCache *cache = [SDImageCache sharedImageCache];
        NSUInteger cacheSize = cache.getDiskCount;
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            NSLog(@"缓存大小(%.2f M)",cacheSize/1000.0/1000);
            
            
            
        }];
        
        
    }];
    
    [[SDImageCache sharedImageCache] clearDisk];
    [[SDImageCache sharedImageCache] clearMemory];
    NSOperationQueue *queue1 = [[NSOperationQueue alloc] init];
    [queue1 addOperationWithBlock:^{
        SDImageCache *cache = [SDImageCache sharedImageCache];
        NSUInteger cacheSize = cache.getDiskCount;
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            NSLog(@"缓存大小(%.2f M)",cacheSize/1000.0/1000);
            
            
            
        }];
        
        
    }];
    
    
    if(CURRENTVERSION <9.0){
        UIAlertView *alert =[[UIAlertView alloc]initWithTitle:nil message:messageStr delegate:self cancelButtonTitle:OKStr otherButtonTitles:nil, nil];
        alert.delegate = self;
        [alert show];
    }else{
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:messageStr preferredStyle:UIAlertControllerStyleAlert];
        
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [self.tbView reloadData];
        [alertController addAction:cancelAction];
        [self presentViewController:alertController animated:YES completion:^{
            
        }];
        
    }
    
}

-(void)exitClick:(UIButton *)btn{
    
    NSNotificationCenter *noti = [NSNotificationCenter defaultCenter];
    saveLoginState(NLOGSTATE);
    //#ifdef Main
    
    //#ifdef Main
    if([getUIStyle() isEqualToString:STYLE0]){
        NSLog(@"主项目程序");
        [noti postNotificationName:@"login" object:@"exit"];
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        [ud removeObjectForKey:@"roleNames"];//将登录人的角色信息清除掉。
        [ud removeObjectForKey:@"personalDic"];//清除个人资料相关数据
        [ud removeObjectForKey:@"cnName"];//清除个人资料相关数据
        [ud synchronize];
        //        [self removeCashes];
        
    }else{
        //#elif Student
        NSLog(@"学员端程序");
        [noti postNotificationName:@"login" object:@"exit"];
        
    }
    //#elif Teacher
    //    NSLog(@"老师端程序");
    //#else
    //    NSLog(@"都不是");
    //#endif
}
- (void)imageBtnClick{
    NSLog(@"有效");
    [self toChoose];
}

- (void)toChoose{
    //    if(_imgArr.count>1){
    [_imgArr removeLastObject];
    //    }
    
    NSString *alertTitleStr = @"";
    NSString *actionTitleStr = @"";
    NSString *cancelStr = @"";
    NSString *AlbumStr = @"“Album”";
    
    //这里添加功能判断
    if (getEnglishLanguage()) {
        alertTitleStr = [NSString stringWithFormat:@"Please select %@ to modify the Avatar",AlbumStr];
        actionTitleStr = @"Album";
        cancelStr = @"Cancel";
    }else{
        alertTitleStr = @"请选择修改头像的图片";
        actionTitleStr = @"相册";
        cancelStr = @"取消";
    }

    UIAlertController * alert = [UIAlertController alertControllerWithTitle:alertTitleStr message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    
    
    UIAlertAction * action1 = [UIAlertAction actionWithTitle:actionTitleStr style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //        PhotoViewController * photo = [[PhotoViewController alloc]init];
        //
        //        __weak typeof(self)weakSelf = self;
        //
        //        photo.popSelectArr = ^(NSMutableArray*arr ){
        //
        //            __strong typeof(self)strongSelf = weakSelf;
        //
        //            strongSelf.imgArr = arr;
        //
        //            UIImage * img = [UIImage imageNamed:@"add-img.png"];
        //
        //            [strongSelf.imgArr addObject:img];
        //
        //            [strongSelf.cv reloadData];
        //
        //          //  NSLog(@"%ld",self.imgArr.count);
        //
        //        };
        //
        //        [self.navigationController pushViewController:photo animated:NO];
        imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
        imagePickerVc.allowPickingOriginalPhoto = NO;
        imagePickerVc.allowPickingVideo = NO;
        __weak __typeof(self)weakSelf = self;
        NSMutableArray<NSString*> *imagePaths = [[NSMutableArray alloc] init];
        ZMView *zmView = [[ZMView alloc]init];
        [imagePickerVc setDidFinishPickingPhotosWithInfosHandle:^(NSArray<UIImage *> *photos,NSArray *assets,BOOL isSelectOriginalPhoto,NSArray<NSDictionary *> *infos){
            
            int index = 0;
            if (userIcon()) {//要新上传头像，需要将之前的头像删除掉
                NSString *usericon = userIcon();
                NSString *paths = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
                NSLog(@"%@",paths);
                NSRange range = [usericon rangeOfString:@"Documents"];
                NSRange needRange = NSMakeRange(0, range.location+range.length);
                usericon = [usericon stringByReplacingCharactersInRange:needRange withString:paths];
                
                NSLog(@"%@",usericon);
                
                NSFileManager *fileMgr = [NSFileManager defaultManager];
                BOOL bRet = [fileMgr fileExistsAtPath:usericon];
                if (bRet) {
                    //
                    NSError *err;
                    [fileMgr removeItemAtPath:usericon error:&err];
                }

            }
            __block NSInteger totalCount = photos.count;
            __block NSInteger curIndex = 0;
            for(NSDictionary* dic in infos){
                UIImage* photo = [photos objectAtIndex:index];
                NSURL* url = [dic objectForKey:@"PHImageFileURLKey"];
                __block NSString* path = [url absoluteString];
                PHAsset* asset = assets[index];
                [asset valueForKey:@"filename"];
                __block NSString* filename = [path lastPathComponent];
                if(filename == nil){
                    [asset requestContentEditingInputWithOptions:nil completionHandler:^(PHContentEditingInput *contentEditingInput, NSDictionary *info){
                        NSURL* fileUrl = contentEditingInput.fullSizeImageURL;
                        filename = [[fileUrl absoluteString] lastPathComponent];
                        path = [zmView saveImageToLocalimage:photo filename:filename];
                        [imagePaths addObject:path];
                        curIndex++;
                        if(curIndex == totalCount){
                            [weakSelf sendPics:imagePaths];
                        }
                    }];
                }else{
//                    _imagePath = [NSString stringWithFormat:@"%@",path];
                    
                    path = [zmView saveImageToLocalimage:photo filename:filename];
                    
                    _imagePath = path;
                    saveUserIcon(path);
                    UIImage *photoImg = [[UIImage alloc]initWithContentsOfFile:path];
                    //                    [imagePaths addObject:path];
                    [imagePaths addObject:photoImg];
//                    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
//                    NSString *ourDocumentPath =[documentPaths objectAtIndex:0];
////                    NSString *sandboxPath = NSHomeDirectory();
////                    NSString *documentPath = [sandboxPath stringByAppendingPathComponent:@"Documents"];
//                    NSString *FileName=[ourDocumentPath stringByAppendingPathComponent:@"头像"];
//                    _imagePath = FileName;
//                    saveUserIcon(FileName);
//                    NSData *data;
//                    if (UIImagePNGRepresentation(photoImg) == nil) {
//                        
//                        data = UIImageJPEGRepresentation(photoImg, 1);
//                        
//                    } else {
//                        
//                        data = UIImagePNGRepresentation(photoImg);
//                    }
//                    [data writeToFile:FileName atomically:YES];
                    
                    
                    
                    [self settitleImage:photoImg];
                    NSLog(@"%d",_imgArr);
                    [self.imgArr addObject:photoImg];
                    
                    curIndex++;
                    if(curIndex == totalCount){
                        [weakSelf sendPics:imagePaths];
                    }
                }
                index++;
                
            }
            
        }];
        
        [self presentViewController:imagePickerVc animated:YES completion:nil];
        
        
    }];
    
//    UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        UIImage * img = [UIImage imageNamed:@"image_attr_normal"];
//        [self.imgArr addObject:img];
//        UIImagePickerController *pick = [[UIImagePickerController alloc] init];
//        pick.sourceType = UIImagePickerControllerSourceTypeCamera;
//        
//        pick.delegate = self;
//        pick.allowsEditing = YES;  //是否可编辑
//        [self presentViewController:pick animated:YES completion:^{
//            
//        }];
//        
//    }];
    
//        UIAlertAction * action3 = [UIAlertAction actionWithTitle:@"视频" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//    
//            UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
//            ipc.sourceType = UIImagePickerControllerSourceTypeCamera;//sourcetype有三种分别是camera，photoLibrary和photoAlbum
//            NSArray *availableMedia = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];//Camera所支持的Media格式都有哪些,共有两个分别是@"public.image",@"public.movie"
//            ipc.mediaTypes = [NSArray arrayWithObject:availableMedia[1]];//设置媒体类型为public.movie
//            [self presentViewController:ipc animated:YES completion:nil];
//            ipc.videoMaximumDuration = 30.0f;//30秒
//            ipc.delegate = self;//设置委托
//            NSLog(@"122");
//        }];
    
    UIAlertAction * action4 = [UIAlertAction actionWithTitle:cancelStr style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        
        
        
//        UIImage * img = [UIImage imageNamed:@"image_attr_normal"];
//        NSLog(@"%@",_imgArr);
        //        [self.imgArr removeObjectAtIndex:0];
        
//        [self.imgArr addObject:img];
//        [self.cv reloadData];
        
    }];
    //
    [alert addAction: action1];
//    [alert addAction: action2];
    //    [alert addAction: action3];
    [alert addAction: action4];
    
    [self presentViewController:alert animated:NO completion:nil];
    
}

- (void)settitleImage:(UIImage *)image{
    _headImg.image = image;
}

#pragma mark - 代理方法 通过这里可以把把图片数组传到相应的界面
-(void) sendPics:(NSMutableArray*)pics{
    if(pics.count>0){
        
        self.imagePaths = pics;
//        UIImage * img = [UIImage imageNamed:@"image_attr_normal"];
        NSLog(@"%@",_imgArr);
        //        [self.imgArr removeObjectAtIndex:0];
        
//        [self.imgArr addObject:img];
//        [self.cv reloadData];
        NSLog(@"%@",_imgArr);
        [self shangchuan];
    
    }
    
}
static int a = 0;
-(void)shangchuan{
    
    
    //    NSLog(@"没服务器你传哪去");
    //    UIImage *iim = self.imgArr[0];
//    return;
    
    if(a>_imgArr.count-1){
        a=0;
        UIAlertController *alert =[UIAlertController alertControllerWithTitle:nil message:@"上传成功" preferredStyle:UIAlertControllerStyleAlert];
//        [self presentViewController:alert animated:YES completion:^{
//        }];
        
        [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(creatAlert:) userInfo:alert repeats:NO];
        return;
        
    }
    if(self.imgArr.count>0){
        NSLog(@"@@@@@@@%lu",(unsigned long)self.imgArr.count);
        //if(self.imgArr.count>1){
        //for(int i=0;i<[self.imgArr count];i++){
        UIImage *iiimm = self.imgArr[a];
        NSData *imageData = UIImagePNGRepresentation(iiimm);
//        _demoView.hidden = NO;
        NSString *requestUrl = [NSString stringWithFormat:@"%@%@", self.programaUrl, POSTPIC];
        [NetRequest postPictures:imageData Url:requestUrl andFieldName:[NSString stringWithFormat:@"%d图片",a+1] andReturnBlock:^(NSData *progress, NSError *error) {
            
            if(!error){
                
                NSString *str =[[NSString alloc]initWithData:progress encoding:NSUTF8StringEncoding];
                NSLog(@"%@++++++++++++++++++++%d",str,a);
                _picString = str;
                
                NSArray *comArr = [str componentsSeparatedByString:@":"];
                if (comArr.count >1) {
                    _fileCount = [comArr objectAtIndex:1];
                }
                NSLog(@"%@",_fileCount);
                [_picArr addObject:str];
                [self requestSave];
            }else{
                NSLog(@"失败");
            }
            a++;
            sss = (float)a/(float)(_imgArr.count-1);
//            _demoView.progressView.progress = sss;
            [self shangchuan];
            
            
        } andFloatProsess:^(CGFloat prosess) {
            NSLog(@"%f", prosess);
            dispatch_sync(dispatch_get_main_queue(), ^{
                //Update UI in UI thread here
            });
            
        }];
        //      _demoView.progressView.progress = ss;
    }
    
    
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:( NSString *)kUTTypeImage]){
        
        //得到图片
        UIImage * image0 = [info objectForKey:UIImagePickerControllerOriginalImage];
        //图片存入相册
        UIImage * img = [UIImage imageNamed:@"image_attr_normal"];
        UIImageWriteToSavedPhotosAlbum(image0, nil, nil, nil);
        NSLog(@"%@",_imgArr);
        [self.imgArr removeLastObject];
        
        [self.imgArr addObject:image0];
        [self.imgArr addObject:img];
        NSLog(@"%@",_imgArr);
//        [self.cv reloadData];
        [self dismissModalViewControllerAnimated:YES];
    }else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]){
        NSURL* mediaURL = [info objectForKey:UIImagePickerControllerMediaURL];
        
        //创建ALAssetsLibrary对象并将视频保存到媒体库
        
        
        ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
        
        // 将视频保存到相册中
        
        [assetsLibrary writeVideoAtPathToSavedPhotosAlbum:mediaURL
                                          completionBlock:^(NSURL *assetURL,NSError *error) {
                                              
                                              if (!error) {
                                                  
                                                  NSLog(@"captured video saved with no error.");
                                                  
                                              }else{
                                                  
                                                  NSLog(@"error occured while saving the video:%@", error);
                                                  
                                              }
                                              
                                          }];
        [self dismissModalViewControllerAnimated:YES];
    }
    
}

- (void)creatAlert:(NSTimer *)timer{
    
    UIAlertController *alert = [timer userInfo];
    
    [alert dismissViewControllerAnimated:YES completion:nil];
    
    alert = nil;
    [self.navigationController popViewControllerAnimated:YES];
    
    NSMutableArray *imgArrs = [[NSMutableArray alloc]initWithArray:_imgArr];
    [imgArrs removeLastObject];
    NSLog(@"%@",_picArr);
    NSLog(@"%@",imgArrs);
//    _picID(_picArr, imgArrs);
    
}
- (void)requestSave{
    NSMutableDictionary *parmas = [[NSMutableDictionary alloc]init];
    //hp://124.254.63.60:8874/edus_auto/update_updateInfo.do?t0_au_2_4171=179&t0_au_2_4171_3569=244&&ifCleanInnerData=undefined&tableId=2&pageId=4171&ifRecordingLog=0
    if (_fileCount) {
        [parmas setObject:_fileCount forKey:@"t0_au_2_4232_3652"];
    }
    
    NSString *user = userId();
    if (user) {
        [parmas setObject:user forKey:@"t0_au_2_4232"];
    }
    //这个是人员表修改页面的头像修改保存按钮的请求参数，教师头像功能更换地址需要修改这里的代码
    [parmas setObject:@"2" forKey:@"tableId"];
    [parmas setObject:@"4232" forKey:@"pageId"];
    [parmas setObject:[NSString stringWithFormat:@"%i", 0] forKey:@"start"];
    [parmas setObject:@"0" forKey:@"ifRecordingLog"];
    [parmas setObject:@"undefined" forKey:@"ifCleanInnerData"];
    
    
    
    
    
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@", self.programaUrl, UPDATEMFSUB_URL];
    //        NSString *urlStr = [NSString stringWithFormat:@"http://124.254.63.60:8874/edus_auto/model_interfaceToList.do?alterTime=&limit=20&loginName=%@&password=%@&pageId=%d&start=0&tableId=%d",loginName,LoginPassWord,_tableId.intValue,_pageId.intValue];//(学员端接口500错误)
    [NetRequest requestUrl:requestUrl andParamas:parmas andReturnBlock:^(NSData *data, NSError *error) {
        if (data!=nil&&!error) {
            NSLog(@"%@",data);
            NSDictionary *obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"%@",obj);
            
        }
    }];
}


-(void)requestUserIconAndSave{
    NSString *str = @"";
    NSString *requestURL =[NSString stringWithFormat:@"%@%@",self.programaUrl,GETPIC];
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    [params setObject:str forKey:@"str"];
    
    
    [NetRequest requestUrl:requestURL andParamas:params andReturnBlock:^(NSData *data, NSError *error) {
        if(data&&!error){
            UIImage *image=[UIImage imageWithData:data];
            [self.imgArr addObject:image];
            ZMView *zmView = [[ZMView alloc]init];
            NSString *path;
            if (userId()) {
                path = [zmView saveImageToLocalimage:image filename:[NSString stringWithFormat:@"%@",userId()]];
            }else{
                path = [zmView saveImageToLocalimage:image filename:@"头像1"];
            }
            
            _imagePath = path;
            saveUserIcon(path);
            _headImg.image = image;
            
                



            
        }else{
            
        }
    }];

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
